﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

using AForge.Video;
using AForge.Video.DirectShow;

namespace CCTV.Video
{
    public static class VideoCapture
    {
        private static FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
        private static VideoCaptureDevice videoSource = null;
        private static int cameraDevice = 0;
        public static Bitmap LastImage = new Bitmap(320,240);

        public static void StartCapture(int w, int h)
        {
            videoSource = new VideoCaptureDevice(videoDevices[cameraDevice].MonikerString);
            videoSource.NewFrame += new NewFrameEventHandler(Video_NewFrame);
            CloseVideoSource();
            videoSource.DesiredFrameSize = new Size(w, h);
            videoSource.Start();
        }

        //eventhandler if new frame is ready
        private static void Video_NewFrame(object sender, NewFrameEventArgs eventArgs)
        {
            lock (LastImage)
            {
                LastImage.Dispose();
                LastImage = (Bitmap)eventArgs.Frame.Clone();
            }
        }

        //close the device safely
        public static void CloseVideoSource()
        {
            if (!(videoSource == null))
            {
                if (videoSource.IsRunning)
                {
                    videoSource.SignalToStop();
                    videoSource = null;
                }

            }
        }

    }
}